#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import time

# 设置标准输出编码为UTF-8（Windows兼容性）
if sys.platform == "win32":
    import io
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
    sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')

def todo_manager():
    """简单的待办事项管理器"""
    todos = []
    
    print("📝 欢迎使用待办事项管理器！")
    print("=" * 40)
    
    while True:
        show_menu()
        
        print("请输入选择 (1-6):")
        
        try:
            choice = int(input())
            
            if choice == 1:
                add_todo(todos)
            elif choice == 2:
                view_todos(todos)
            elif choice == 3:
                complete_todo(todos)
            elif choice == 4:
                delete_todo(todos)
            elif choice == 5:
                search_todos(todos)
            elif choice == 6:
                print("感谢使用！再见！👋")
                break
            else:
                print("❌ 无效选择，请输入 1-6 之间的数字！")
                
        except ValueError:
            print("❌ 请输入有效的数字！")
        except KeyboardInterrupt:
            print("\n\n程序被用户中断")
            break

def show_menu():
    """显示主菜单"""
    print("\n" + "=" * 40)
    print("📋 待办事项管理菜单")
    print("=" * 40)
    print("1. ➕ 添加待办事项")
    print("2. 📖 查看所有待办事项")
    print("3. ✅ 标记完成")
    print("4. 🗑️  删除待办事项")
    print("5. 🔍 搜索待办事项")
    print("6. 🚪 退出程序")
    print("=" * 40)

def add_todo(todos):
    """添加待办事项"""
    print("\n➕ 添加新的待办事项")
    print("-" * 20)
    
    print("请输入待办事项描述:")
    description = input().strip()
    
    if not description:
        print("❌ 描述不能为空！")
        return
    
    print("请输入优先级 (高/中/低, 默认为中):")
    priority = input().strip()
    if not priority:
        priority = "中"
    elif priority not in ["高", "中", "低"]:
        print("⚠️ 无效优先级，设置为中等")
        priority = "中"
    
    todo = {
        'id': len(todos) + 1,
        'description': description,
        'priority': priority,
        'completed': False,
        'created_time': time.strftime("%Y-%m-%d %H:%M:%S")
    }
    
    todos.append(todo)
    print(f"✅ 成功添加待办事项: {description}")

def view_todos(todos):
    """查看所有待办事项"""
    if not todos:
        print("\n📭 暂无待办事项")
        return
    
    print(f"\n📖 所有待办事项 (共 {len(todos)} 项)")
    print("-" * 60)
    
    # 按优先级排序
    priority_order = {"高": 1, "中": 2, "低": 3}
    sorted_todos = sorted(todos, key=lambda x: (x['completed'], priority_order.get(x['priority'], 2)))
    
    for todo in sorted_todos:
        status = "✅" if todo['completed'] else "⏳"
        priority_icon = {"高": "🔴", "中": "🟡", "低": "🟢"}.get(todo['priority'], "🟡")
        
        print(f"{status} [{todo['id']}] {priority_icon} {todo['description']}")
        print(f"    优先级: {todo['priority']} | 创建时间: {todo['created_time']}")
        print()

def complete_todo(todos):
    """标记待办事项为完成"""
    if not todos:
        print("\n📭 暂无待办事项")
        return
    
    view_todos(todos)
    
    print("请输入要标记完成的待办事项ID:")
    
    try:
        todo_id = int(input())
        
        for todo in todos:
            if todo['id'] == todo_id:
                if todo['completed']:
                    print("ℹ️ 该待办事项已经完成了")
                else:
                    todo['completed'] = True
                    print(f"✅ 已标记完成: {todo['description']}")
                return
        
        print("❌ 找不到指定ID的待办事项")
        
    except ValueError:
        print("❌ 请输入有效的数字ID")

def delete_todo(todos):
    """删除待办事项"""
    if not todos:
        print("\n📭 暂无待办事项")
        return
    
    view_todos(todos)
    
    print("请输入要删除的待办事项ID:")
    
    try:
        todo_id = int(input())
        
        for i, todo in enumerate(todos):
            if todo['id'] == todo_id:
                print(f"确定要删除 '{todo['description']}' 吗？(y/n):")
                confirm = input().lower().strip()
                
                if confirm in ['y', 'yes', '是']:
                    deleted_todo = todos.pop(i)
                    print(f"🗑️ 已删除: {deleted_todo['description']}")
                else:
                    print("❌ 取消删除")
                return
        
        print("❌ 找不到指定ID的待办事项")
        
    except ValueError:
        print("❌ 请输入有效的数字ID")

def search_todos(todos):
    """搜索待办事项"""
    if not todos:
        print("\n📭 暂无待办事项")
        return
    
    print("请输入搜索关键词:")
    keyword = input().strip().lower()
    
    if not keyword:
        print("❌ 搜索关键词不能为空")
        return
    
    results = []
    for todo in todos:
        if keyword in todo['description'].lower():
            results.append(todo)
    
    if not results:
        print(f"🔍 没有找到包含 '{keyword}' 的待办事项")
        return
    
    print(f"\n🔍 搜索结果 (找到 {len(results)} 项)")
    print("-" * 40)
    
    for todo in results:
        status = "✅" if todo['completed'] else "⏳"
        priority_icon = {"高": "🔴", "中": "🟡", "低": "🟢"}.get(todo['priority'], "🟡")
        
        print(f"{status} [{todo['id']}] {priority_icon} {todo['description']}")
        print(f"    优先级: {todo['priority']} | 创建时间: {todo['created_time']}")
        print()

if __name__ == "__main__":
    try:
        todo_manager()
    except Exception as e:
        print(f"\n❌ 程序出现错误: {e}")
        sys.exit(1)
